﻿using System.Windows;
using System.Windows.Input;

namespace Microsoft.Xna.Framework.Input
{
    /// <summary>
    /// Allows retrieval of position and button clicks from a mouse input device.
    /// </summary>
    public class Mouse
    {
		private static MouseState state;

        // Since there's no way to detect whether the mouse is on or off the
        // game window at a given time
        private static bool IsOnGameWindow = true;

		internal static void Initialize()
		{
			state = new MouseState();

			Application.Current.RootVisual.MouseEnter += new MouseEventHandler(RootVisual_MouseEnter);
			Application.Current.RootVisual.MouseLeave += new MouseEventHandler(RootVisual_MouseLeave);
			Application.Current.RootVisual.MouseLeftButtonDown += new MouseButtonEventHandler(RootVisual_MouseLeftButtonDown);
			Application.Current.RootVisual.MouseLeftButtonUp += new MouseButtonEventHandler(RootVisual_MouseLeftButtonUp);
			Application.Current.RootVisual.MouseWheel += new MouseWheelEventHandler(RootVisual_MouseWheel);
			Application.Current.RootVisual.MouseMove += new MouseEventHandler(RootVisual_MouseMove);
		}

		#region Private Methods
		static void RootVisual_MouseEnter(object sender, MouseEventArgs e)
		{
			IsOnGameWindow = true;
		}

		static void RootVisual_MouseLeave(object sender, MouseEventArgs e)
		{
			IsOnGameWindow = false;
		}

		static void RootVisual_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
		{
			state.LeftButton = ButtonState.Pressed;
		}

		static void RootVisual_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
		{
			state.LeftButton = ButtonState.Released;
		}

		static void RootVisual_MouseMove(object sender, MouseEventArgs e)
		{
			System.Windows.Point p = e.GetPosition(Application.Current.RootVisual);
			state.X = (int)p.X;
			state.Y = (int)p.Y;
		}

		static void RootVisual_MouseWheel(object sender, MouseWheelEventArgs e)
		{
			state.ScrollWheelValue += e.Delta;
		}
		#endregion

		#region Public Methods
		/// <summary>
        /// Gets the current state of the mouse, including mouse position and buttons pressed.
        /// </summary>
        public static MouseState GetState()
        {
            return state;
        }

		/// <summary>
		/// Sets the position of the mouse cursor relative to the upper-left corner of the window.
		/// </summary>
		/// <param name="x">The horizontal position of the mouse cursor, relative to the left edge of the game window.</param>
		/// <param name="y">The vertical position of the mouse cursor, relative to the left edge of the game window.</param>
		public static void SetPosition(int x, int y)
		{
			// due to obvious security risks, this doesn't work, but we have to provide the stub for compatibility.
		}
		#endregion
	}
}